﻿using Engine;
using Game;
using GameEntitySystem;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SCIENEW
{
	public class TransferElectricElement : ElectricElement
	{
		public bool m_isDispenseAllowed = true;

		public double? m_lastDispenseTime;

		public SubsystemBlockEntities m_subsystemBlockEntities;
		public SubsystemTerrain m_subsystemTerrain;

		public TransferElectricElement(SubsystemElectricity subsystemElectricity, Point3 point) : base(
			subsystemElectricity,
			new List<CellFace> {
				new(point.X, point.Y, point.Z, 0),
				new(point.X, point.Y, point.Z, 1),
				new(point.X, point.Y, point.Z, 2),
				new(point.X, point.Y, point.Z, 3),
				new(point.X, point.Y, point.Z, 4),
				new(point.X, point.Y, point.Z, 5)
			}
		)
		{
			m_subsystemBlockEntities = SubsystemElectricity.Project.FindSubsystem<SubsystemBlockEntities>(throwOnError: true);
			m_subsystemTerrain = SubsystemElectricity.Project.FindSubsystem<SubsystemTerrain>(throwOnError: true);
		}

		public override bool Simulate()
		{
			if (CalculateHighInputsCount() > 0 && (!m_lastDispenseTime.HasValue || SubsystemElectricity.SubsystemTime.GameTime - m_lastDispenseTime > 0.1))
			{
				int cellValue = m_subsystemTerrain.Terrain.GetCellValue(CellFaces[0].Point.X, CellFaces[0].Point.Y, CellFaces[0].Point.Z);
				//int num = 0;
				int face = DevicesUtils.GetInnerData(cellValue);
				Vector3 vector1 = CellFace.FaceToVector3(face);
				Vector3 vector2 = -CellFace.FaceToVector3(face);
				var blockEntity1 = m_subsystemBlockEntities.GetBlockEntity(CellFaces[0].Point.X + (int)vector1.X, CellFaces[0].Point.Y + (int)vector1.Y, CellFaces[0].Point.Z + (int)vector1.Z);
				var blockEntity2 = m_subsystemBlockEntities.GetBlockEntity(CellFaces[0].Point.X + (int)vector2.X, CellFaces[0].Point.Y + (int)vector2.Y, CellFaces[0].Point.Z + (int)vector2.Z);
				bool placed = false;
				if (blockEntity1 != null && blockEntity2 != null)
				{
					var component1 = blockEntity1.Entity.FindComponent<ComponentInventoryBase>();
					var component2 = blockEntity2.Entity.FindComponent<ComponentInventoryBase>();
					if (component1 != null && component2 != null && component1.SlotsCount >= component2.SlotsCount)
					{
						for (int i=0; i<component2.SlotsCount; i++)
						{
							if (component1.m_slots[i].Count==0 || component1.m_slots[i].Value == component2.m_slots[i].Value)
							{
								component1.AddSlotItems(i, component2.m_slots[i].Value, component2.m_slots[i].Count);
								component2.RemoveSlotItems(i, component2.m_slots[i].Count);
							}
						}
					}

				}
				if (placed)
					m_lastDispenseTime = SubsystemElectricity.SubsystemTime.GameTime;
			}
			return false;
		}
	}
}
